package test.lemonyfei.http.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * Created by sh00556 on 2017/4/25.
 */
public class FileUtils {
    private static Scanner scanner;

    public static String readFile(String filename) {
        String content = null;
        File file = new File(filename);
        FileReader reader = null;
        try {
            reader = new FileReader(file);
            char[] chars = new char[(int) file.length()];
            reader.read(chars);
            content = new String(chars);
            reader.close();
        } catch (IOException e1) {
            e1.printStackTrace();
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content;
    }

    public static String readFirstLineOfFile(String filename) {
        String responseCode = "";
        try {
            scanner = new Scanner(new File(filename));
            if (scanner.hasNextLine()) {
                responseCode = scanner.nextLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return responseCode;
    }

    public static String readFileWithoutFirstLine(String filename) {
        ArrayList<String> content = readConfigFile(filename);
        String responseBody = "";
        for (int i = 1; i < content.size(); i++) {
            responseBody = responseBody + content.get(i);
            responseBody = responseBody + "\n";
        }
        return responseBody;
    }

    public static ArrayList<String> readConfigFile(String filename) {
        ArrayList<String> content = new ArrayList();
        try {
            scanner = new Scanner(new File(filename));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                content.add(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return content;
    }

}
